package hevs.activities;

import hevs.greencontrol.R;
import hevs.greencontrol.R.drawable;
import hevs.greencontrol.R.id;
import hevs.greencontrol.R.layout;
import hevs.utils.ConnectionManager;
import hevs.utils.Utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This class allow the user to select the smart objects to control.
 * @author Jonathan Moreira, Jun Yang, Natal Venetz, Ivan Samardziev
 *
 */
public class Selector extends Activity implements OnClickListener{
    
	// DATA
	private final static String LOGIN="login.txt";
	private ListView listView;
	private TextView text;
	private AlertDialog editDialog;
	private AlertDialog deleteConfirmation;
	private AlertDialog exitConfirmation;
	private AlertDialog helpDialog;
	//private UserData userData;
	private Activity currentActivity;
	private String list[]={"Room1","Room2","Room3","Room4"};
	/**
	 * Method called on creation of activity
	 */
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selector);
        
        // set the current activity
        currentActivity = this;
        
        // instanciate the user data
       // userData = UserData.getInstance();
        
        // instanciate the textView
        text = (TextView) this.findViewById(R.id.textView_selectRobots);
        
		 // instanciate the listView
        listView = (ListView)findViewById(R.id.listView);
        
        
        // instaciate the dialogs
        editDialog = new AlertDialog.Builder(this).create();
        deleteConfirmation = new AlertDialog.Builder(this).create();
        exitConfirmation = new AlertDialog.Builder(this).create();
        helpDialog = new AlertDialog.Builder(this).create();
    }
    
	/**
	 * Method called on start of activity
	 */
	@Override
	protected void onStart()
	{
		super.onStart();
		
		//initiate the edit dialog
		initEditDialog();
		initDeleteConfirmation();
		initExitConfirmation();
		initHelpDialog();
		
//		if(userData.getMapToEdit() != null)
//		{
//			userData.setMapToEdit(null);
//	        // We load the smart objects into the list
//			ConnectionManager.getObjectsByIdUser(userData.getIdUser(), this);
//		}
			
		// set the list view
       // listView.setAdapter(new ArrayAdapter<String>(this,
        //		android.R.layout.simple_list_item_1, userData.getListMapDescription()));

		
	       listView.setAdapter(new ArrayAdapter<String>(this,
        		android.R.layout.simple_list_item_1, list));
        
        // add a click listener
        listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
			{
				Toast.makeText(getApplicationContext(), "Ouvre une nouvelle page", 1);
				startActivity(new Intent(currentActivity,MapPlan.class));
			}
		});
        
        // add a long click listener
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
        {
        	@Override
        	public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id)
        	{
				//userData.setMapToEdit(userData.getMap(position));
        		editDialog.show();
        		return false;
        	}
        });
        
//        if(userData.getListMaps().size() == 0)
//        {
//        	//change text
//        	text.setText("No Map registered");
//        }

	}

	/**
	 * Method used to initiate the edit dialog
	 */
	private void initEditDialog()
	{
		editDialog.setIcon(R.drawable.ic_edit);
		editDialog.setTitle("Edit a map");
		editDialog.setMessage("What do you want to do ?");
		
		// edit button :
		editDialog.setButton("Edit", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which)
			{			
				startActivity(new Intent(currentActivity,MapPlan.class));
			}
		});

		// delete button :
		editDialog.setButton2("Delete", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which)
			{
				deleteConfirmation.show();
			}
		});
////		editDialog.setOnCancelListener(new OnCancelListener()
////		{
////		    @Override
//////		    public void onCancel(DialogInterface arg0)
//////		    {
//////		    	userData.setMapToEdit(null);
//////		    }
//		});


	}

	/**
	 * Method initiate the delete confirmation dialog
	 */
	private void initDeleteConfirmation()
	{
		deleteConfirmation.setIcon(R.drawable.ic_tab_cross);
		deleteConfirmation.setTitle("Delete confirmation");
		deleteConfirmation.setMessage("Are you sure you want to delete this map ?");
		
		
		// yes button :
		deleteConfirmation.setButton("Yes", new DialogInterface.OnClickListener()
		{	
			public void onClick(DialogInterface dialog, int which)
			{
				boolean pass = false;
				ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
			//	nameValuePairs.add(new BasicNameValuePair("mapID",userData.getMapToEdit().getId()+""));
				JSONArray jArray = ConnectionManager.sendhttpPost("deleteObject.php", nameValuePairs);
				pass = Utils.getCRUDconfirmation(jArray, "Delete", Selector.this);
				
				if(pass)
				{
					startActivity(new Intent(currentActivity,Selector.class));
				}
			}
			
		});

		// no button :
		deleteConfirmation.setButton2("No", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which)
			{
				deleteConfirmation.cancel();
			}
		});
		
		deleteConfirmation.setOnCancelListener(new OnCancelListener()
		{
		    @Override
		    public void onCancel(DialogInterface arg0)
		    {
		    //	userData.setMapToEdit(null);
		    }
		});
	}
	
	/**
	 * Method used to initiate the exit confirmation dialog
	 */
	private void initExitConfirmation()
	{
		exitConfirmation.setIcon(R.drawable.ic_exit);
		exitConfirmation.setTitle("Exit");
		exitConfirmation.setMessage("Are you sure you want to exit the application ?");
		
		
		// yes button :
		exitConfirmation.setButton("Yes", new DialogInterface.OnClickListener()
		{	
			public void onClick(DialogInterface dialog, int which)
			{
				moveTaskToBack(true);
				currentActivity.finish();
			}
		});

		// no button :
		exitConfirmation.setButton2("No", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which)
			{
			}
		});		
	}
	
	/**
	 * Method used to initiate the help dialog
	 */
	private void initHelpDialog()
	{
		helpDialog.setTitle("How to edit a map ?");
		helpDialog.setMessage("To edit a map, press over the desired item for a few seconds.");
		
		helpDialog.setButton("Ok", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which)
			{
			}
		});

		helpDialog.setIcon(android.R.drawable.ic_menu_help);
	}
    
	
	/**
	 * Action on back pressed
	 */
	@Override
	public void onBackPressed()
	{
		exitConfirmation.show();
	}
	
	//***********************************************************************************************  
	// Option menu :
	//*********************************************************************************************** 

	/**
	 * Create the option menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		menu.add(0, 1000, 0, "Add a map").setIcon(android.R.drawable.ic_menu_add) ;
		menu.add(0, 1003, 1, "Help").setIcon(android.R.drawable.ic_menu_help) ;
		menu.add(0, 1001, 2, "Credits").setIcon(android.R.drawable.btn_star) ;
		menu.add(0, 1002, 3, "Logout").setIcon(android.R.drawable.ic_menu_close_clear_cancel) ;

		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * Switch the actions when executed on menu item click
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		switch (item.getItemId()) {

		case 1000:
			//Add a robot :
			//startActivity(new Intent(this,ListRobotTypes.class));
			break;

		case 1001:
			//Credits :
			//startActivity(new Intent(this,Credits.class));
			break;

		case 1002:
			//Logout :
			logout();
			startActivity(new Intent(this,StartPage.class));
			this.finish(); 
			break;
			
		case 1003:
			helpDialog.show();
			break;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}
	
	/**
	 * Method used to logout the application
	 */
	private void logout()
	{	
		try
		{
			// We get the username 
			InputStream inputStream = openFileInput(LOGIN);
			
			String un = "";
			String pw = "";
			
			if (inputStream != null)
			{
				InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
				BufferedReader reader = new BufferedReader(inputStreamReader);
	
				// read automatic login
				reader.readLine();
				
				// read username
				un = reader.readLine();
				
				// read password
				pw = reader.readLine();
	
				inputStream.close();
				
				// Now we set the automatic login to false and we rewrite the username
				OutputStreamWriter output = new OutputStreamWriter(openFileOutput(LOGIN, 0));
				output.write("false" + "\n" + un + "\n" + pw);
				output.close();
			}
		}
		catch (java.io.FileNotFoundException e)
		{
			// file login.txt not created
		}
		catch (Throwable t)
		{
			Toast.makeText(this, "Exception : " + t.toString(), 2000).show();
		}
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}
}